package org.duiduo.sdk.alipay;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.duiduo.sdk.alipay.dto.AliPay;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Data
@Slf4j(topic = "AlipayReqHandler")
@Component
public class AlipayReqHandler {

    private String appId = "2021000118634443";
    private String appPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDf0OHQ/IsksmxzHvbJbSvzY61HaOdNtnu4WK0X06ZxXlYfOpPTgxMROZEyuzRKQn6bQQD5DYL65BVdVKfgWi91iJEsrnhx201igBgXgi7YwjpdovQFSHRXaCHHhcmzh14MnT4e0TAeX9cKKXkiILubvl30ZQq49UlG1mMGXKpmgqDPbT8Cxn5T7sU00+o9mCsX3SIyCLOsNGs3Ejet9e1bQGQMxPBXCe9foYJrVnEYLLJczWQGXU28XwHTjTTT2Xva4/6mBVtXjOrutbMm6CelQs7d7rh1acrF7BJlNrgjxNZ0QBWx667e+5WYAbYcxfNMi6DOVtW76J7cqig4q4mlAgMBAAECggEAcmt3BkAVYk1U5AWQZKlLLsJmc3tNxIzl8vhihSvOi2aO4Kgxqo/3z3Z+pFDQCqaz0usIdEpUC69OvMfqiueQG6YVkaIgMRTMGu8hYeNLz8R70iLcXVcNIyI5Iqdi1kT977TzbQ3Ea8LTTH6nTqstPhG0NpzxPl0neO9g8H+vHXf1viyqsyI6NBTCyelPfZu6ATW4kjHPqa6aqWwZtkBdKW5A7ZG2F70bXWoQXIhjxtjHVxSbcskGGLYw3veoE9MljZ9+E38wEB917guBG/SJiDhSuV/b1hvrZC8e/BO8Kbkt1XVEvo60Gu8VGNltxxedcOoFzeFHAvNI9uMk9Ai0AQKBgQDw/CVywP2SWA/dxS4YktKudJkMY6B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q2FdhLDHX86zsjXrlWwaGu933wPX4DHzh6eRoyBqFUdL0fmy+8/Y9Wtx/dbOQUZEhpJ3koh0loIMiSMxU55FVq/1wF7sw/5rxUp3sp37pNYt51d6TvXzRh5NShZ1+sJlWpKc3tLY/X2xp3Msn66FTU7l4khWBw+7PMLm7A3rfVztgJ1EbjljNjmkltwIDAQAB";
    private String notifyUrl = "http://duiduo.nat300.top/alipay/notify";

    private Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipaydev.com";
        config.signType = "RSA2";
        return config;
    }

    @PostConstruct
    public void init() {
        // 设置参数（全局只需设置一次）
        Config options = getOptions();
        options.appId = this.appId;
        options.merchantPrivateKey = this.appPrivateKey;
        options.alipayPublicKey = this.alipayPublicKey;
        options.notifyUrl = this.notifyUrl;
        Factory.setOptions(options);
        log.info("=======支付宝SDK初始化成功=======");
    }

    /**
     * 沙箱支付
     */
    public static String pay(AliPay aliPay) {
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(aliPay.getSubject(), aliPay.getTraceNo(), aliPay.getTotalAmount(), "");
        } catch (Exception e) {
            log.error("调用遭遇异常，原因：", e);
            throw new RuntimeException(e.getMessage(), e);
        }
        return response.getBody();
    }

    /**
     * 支付宝回调 验签 并返回结果集
     */
    public static Map<String, String> callbackGetParams(HttpServletRequest request) {
        try {
            if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
                log.info("=========支付宝异步回调========");

                Map<String, String> params = new HashMap<>();
                Map<String, String[]> requestParams = request.getParameterMap();
                for (String name : requestParams.keySet()) {
                    params.put(name, request.getParameter(name));
                }

                // 支付宝验签
                if (Factory.Payment.Common().verifyNotify(params)) {
                    // 验签通过
                    log.info("交易名称:{}", params.get("subject"));
                    log.info("交易状态:{}", params.get("trade_status"));
                    log.info("支付宝交易凭证号:{}", params.get("trade_no"));
                    log.info("商户订单号:{}", params.get("out_trade_no"));
                    log.info("交易金额:{}", params.get("total_amount"));
                    log.info("买家在支付宝唯一id:{}", params.get("buyer_id"));
                    log.info("买家付款时间:{}", params.get("gmt_payment"));
                    log.info("买家付款金额:{}", params.get("buyer_pay_amount"));
                    return params;
                }
            }
            throw new RuntimeException("支付宝回调验签失败");
        } catch (Exception e) {
            log.error("调用遭遇异常，原因：", e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
